<template>
  <div class="news-list">
    <h1>News List</h1>
    
    <!-- Search form -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="Keyword">
          <el-input v-model="queryParams.keyword" placeholder="Search keywords" />
        </el-form-item>
        <el-form-item label="Category">
          <el-select v-model="queryParams.category" placeholder="All Categories">
            <el-option v-for="item in categories" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">Search</el-button>
          <el-button @click="resetQuery">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- News table -->
    <el-table v-loading="loading" :data="newsList" stripe border>
      <el-table-column prop="title" label="Title" />
      <el-table-column prop="author" label="Author" width="120" />
      <el-table-column prop="category" label="Category" width="120" />
      <el-table-column prop="publishDate" label="Publish Date" width="180" />
      <el-table-column label="Operations" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="viewNewsDetail(row.id)">View</el-button>
          <el-button type="primary" size="small" @click="editNews(row)">Edit</el-button>
          <el-button type="danger" size="small" @click="confirmDelete(row.id)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNewsList, getNewsCategories, deleteNews } from '@/api/news'
import type { NewsItem, NewsQueryParams } from '@/api/news'

// State
const loading = ref(false)
const newsList = ref<NewsItem[]>([])
const total = ref(0)
const categories = ref<string[]>([])

// Query parameters
const queryParams = reactive<NewsQueryParams>({
  page: 1,
  pageSize: 10,
  keyword: '',
  category: ''
})

// Fetch news list
const fetchNewsList = async () => {
  loading.value = true
  try {
    const response = await getNewsList(queryParams)
    newsList.value = response.data?.list || []
    total.value = response.data?.total || 0
  } catch (error) {
    console.error('Failed to fetch news list:', error)
    ElMessage.error('Failed to load news list')
  } finally {
    loading.value = false
  }
}

// Fetch categories
const fetchCategories = async () => {
  try {
    const response = await getNewsCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}

// Handlers
const handleSearch = () => {
  queryParams.page = 1
  fetchNewsList()
}

const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.category = ''
  queryParams.page = 1
  fetchNewsList()
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  fetchNewsList()
}

const handleCurrentChange = (val: number) => {
  queryParams.page = val
  fetchNewsList()
}

const viewNewsDetail = (id: string) => {
  // Navigate to detail page
  console.log('View news:', id)
}

const editNews = (row: NewsItem) => {
  // Navigate to edit page
  console.log('Edit news:', row)
}

const confirmDelete = (id: string) => {
  ElMessageBox.confirm('Are you sure you want to delete this news?', 'Warning', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteNews(id)
      ElMessage.success('Deleted successfully')
      fetchNewsList()
    } catch (error) {
      console.error('Failed to delete news:', error)
      ElMessage.error('Failed to delete news')
    }
  }).catch(() => {
    // Cancelled
  })
}

// Lifecycle
onMounted(() => {
  fetchNewsList()
  fetchCategories()
})
</script>

<style scoped>
.news-list {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 